package com.jlf.core.output;

import com.jlf.core.error.Code;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.Collection;

/**
 * 输出结果的统一封装
 *
 * @author wujr
 * 2023/7/13
 * @version 1.0
 * 【变更历史】
 * [wujr 2023/7/13 1.0 新增]
 */
@Getter
@Setter
@NoArgsConstructor
public class ResultWrapper<T> implements Serializable {
    public static final ResultWrapper<Object> DEFAULT_OK = new ResultWrapper<>(0, "成功");
    private Integer code;
    private String message;
    private T data;

    ResultWrapper(T data){
        this.data = data;
        this.code = Code.SUCCEED;
        this.message = "成功";
    }
    ResultWrapper(Integer code, String message){
        this.code = code;
        this.message = message;
        this.data = null;
    }

    public static VoidResultWrapper error(Code code, String message) {
        return ResultWrapper.error(code.getError(), StringUtils.isBlank(message) ? code.getMessage() : message);
    }
    public static VoidResultWrapper error(Code code) {
        return ResultWrapper.error(code.getError(), code.getMessage());
    }
    public static VoidResultWrapper error(Integer code) {
        return ResultWrapper.error(code, null);
    }
    public static VoidResultWrapper error(ResultException e) {
        return ResultWrapper.error(e.getError(), e.getMessage());
    }
    public static VoidResultWrapper error(Integer code, String message) {
        return new VoidResultWrapper(code, message);
    }
    public static <T> ResultWrapper<T> ok(T body){
        return new ResultWrapper<>(body);
    }
//    public static <T> ResultWrapper<ListResultWrapper<T>> ok(List<T> body){
//        ListResultWrapper<T> data = new ListResultWrapper<>(body);
//        return new ResultWrapper<>(data);
//    }
    public static <T> ResultWrapper<ListResultWrapper<T>> ok(Collection<T> body){
        ListResultWrapper<T> data = new ListResultWrapper<>(body);
        return new ResultWrapper<>(data);
    }
    public static <T> ResultWrapper<ListResultWrapper<T>> ok(T[] body){
        ListResultWrapper<T> data = new ListResultWrapper<>(body);
        return new ResultWrapper<>(data);
    }

    public boolean success(){
        return Code.SUCCEED.equals(code);
    }

    public byte[] jsonBytes(){
        return new JSONObject(this).toString().getBytes(Charset.defaultCharset());
    }
    public String json(){
        return new JSONObject(this).toString();
    }
}